package day22;

import java.util.concurrent.*;

public class MyThreadPool {
    //先定义七个参数
    //1.定义核心参数:设置规则一般是通过电脑自己的Cpu数决定的
    private static final int core_num = Runtime.getRuntime().availableProcessors();
    //2.最大核心线程数：设置规则一般是设置成核心线程数的两倍
    private static final int max_num = 20;
    //3.定义（多余线程 = 最大数量 - 核心线程数）存活时间
    private static final long alive_time = 30;
    //4.定义时间单位
    private static final TimeUnit unit = TimeUnit.MINUTES;
    //5.工作队列
    private static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(core_num);
    //6.线程工厂
    private static ThreadFactory factory = Executors.defaultThreadFactory();
    //7.拒绝策略
    private static RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
    //8.定义线程池对象
    private  static ExecutorService pool = new ThreadPoolExecutor(
            core_num, max_num, alive_time, unit, queue, factory, handler
    );
    //9.执行自定义线程池的任务  参考execute()
    //返回值true表示执行成功  false执行失败
    public static boolean myExecute(Runnable r) {
        try {
            pool.execute(r);
            return true;
        }
        catch (Exception e) {
            System.out.println("任务执行失败");
            return false;
        }
    }
    //10.执行线程池中的任务
    //访问修饰符  静态的 <S>自定义泛型
    public static <S> Future<S> myExecute(Callable<S> c){
        Future f = null;
        try {
            f = pool.submit(c);
        }catch (Exception e) {
            System.out.println("任务执行失败");
        }
        return f;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        for (int i = 0; i < 10; i++) {
            //传入任务Runnable类型
            MyThreadPool.myExecute(()->{
                System.out.println("ok");
            });
            MyThreadPool.myExecute(()->{
                System.out.println("okok");
            });
            Future<Integer> f = MyThreadPool.myExecute(()->{
                System.out.println("okok");
                return 123;
            });
            System.out.println("callable结果:"+ f.get());
        }
        pool.shutdown();
    }
}
